package com.gsmr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gsmr.entity.PageBean;
import com.gsmr.entity.SDCCH;
import com.gsmr.entity.Decoding;
import com.gsmr.service.DecodingService;
import com.gsmr.util.DateUtil;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
* @author 作者 : 黄志新
* @version 创建时间：2017年8月10日 下午9:17:10
* 类说明：
*/
@Controller
@RequestMapping("/decoding")
public class DecodingController {

	@Resource
	private DecodingService decodingService;
	
	
	/**
	 * 分页条件查询Decoding
	 * @param page
	 * @param rows
	 * @param s_user
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public String list(
			@RequestParam(value="page",required=false)String page,
			@RequestParam(value="rows",required=false)String rows,
			@RequestParam(value="startTime",required=false)String startTime,
			@RequestParam(value="endTime",required=false)String endTime,
			@RequestParam(value="deviceNumber",required=false)String deviceNumber,
			@RequestParam(value="IMSI",required=false)String IMSI,
			@RequestParam(value="MSISDN",required=false)String MSISDN,
			@RequestParam(value="CTCS_ID",required=false)String CTCS_ID,
			@RequestParam(value="kilometerStart",required=false)String kilometerStart,
			@RequestParam(value="kilometerEnd",required=false)String kilometerEnd,
			@RequestParam(value = "search", required = false) String search,
			Decoding decoding,HttpServletResponse response)throws Exception{
		if(search==null){
			return null;
		}
		System.out.println("Decoding startTime:" + startTime);
		System.out.println("Decoding endTime:" + endTime);
		PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("DeviceNumber", StringUtil.formatLike(deviceNumber));
		map.put("IMSI", IMSI);
		map.put("MSISDN", MSISDN);
		map.put("CTCS_ID", CTCS_ID);
		map.put("kilometerStart", kilometerStart);
		map.put("kilometerEnd", kilometerEnd);
		map.put("start", pageBean.getStart());
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		//当天00:00的时间戳
		Long earlyMorningTime = System.currentTimeMillis()/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();
		//当前时间戳
		Long nowTime = System.currentTimeMillis();
		if(startTime!=null&&!startTime.equals("NaN")){
			map.put("startTime", startTime);
		}
		else {
			 map.put("startTime", null);
		}
		if(endTime!=null&&!endTime.equals("NaN")){
			map.put("endTime", endTime);
		}
		else {
			map.put("endTime", null);
		}
		
		map.put("size", pageBean.getPageSize());
		map.put("table_name", "framedata1");
		
		long findDataStartTime = System.currentTimeMillis();
		
		List<Decoding> decodingList = decodingService.find(map);
		
		long findDataEndTime = System.currentTimeMillis();
		
		//Long total=decodingService.getTotal(map);
		int total = Integer.MAX_VALUE;
		long findTotalEndTime = System.currentTimeMillis();
		System.out.println("查找"+pageBean.getPageSize()+"条TCH业务解码数据花的时间（毫秒）"+(findDataEndTime-findDataStartTime));
		System.out.println("查找"+pageBean.getPageSize()+"条TCH业务解码数据对应的总量花的时间（毫秒）"+(findTotalEndTime-findDataEndTime));
		
		JSONObject result=new JSONObject();
		JSONArray jsonArray=JSONArray.fromObject(decodingList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	
	/**
	 * 添加或者修改Decoding
	 * @param Decoding
	 * @param response
	 * @param flag 1 添加  2修改
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(Decoding decoding,HttpServletResponse response,Integer flag)throws Exception{
		int resultTotal=0; // 操作的记录条数
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("table_name", "framedata1");
		map.put("id", decoding.getId());
		map.put("hdlc_id", decoding.getHdlc_id());
		map.put("TriggerTime", decoding.getStartTime());
		map.put("MSISDN", decoding.getMSISDN());
		map.put("IMSI", decoding.getIMSI());
		map.put("CTCS_ID", decoding.getCTCS_ID());
		map.put("TrainNumber", decoding.getTrainNumber());
		map.put("VicroadNumber", decoding.getVicroadNumber());
		map.put("DeviceNumber", decoding.getMSISDN());
		map.put("PortNumber", decoding.getPortNumber());
		map.put("TimeslotNumber", decoding.getTimeSlot());
		map.put("RBCName", decoding.getRBCName());
		map.put("RBCNumber", decoding.getRBCNumber());
		map.put("Q_DIR", decoding.getQ_DIR());
		map.put("CRCTest", decoding.getCRCTest());
		map.put("NID_LRBG", decoding.getNID_LRBG());
		map.put("Q_MPOSITION", decoding.getQ_MPOSITION());
		map.put("Speed", decoding.getSpeed());
		map.put("SignalType", decoding.getSignalType());
		map.put("LLayer", decoding.getLLayer());
		map.put("TLayer", decoding.getTLayer());
		map.put("SLayer", decoding.getSLayer());
		map.put("ALayer", decoding.getALayer());
		map.put("UUID", decoding.getUUID());
		if(flag==1){
			resultTotal=decodingService.add(map);
		}else{
			resultTotal=decodingService.update(map);
		}
		JSONObject result=new JSONObject();
		if(resultTotal>0){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 删除Decoding
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String delete(@RequestParam(value="id")String id,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		JSONObject result=new JSONObject();
		try {
			map.put("table_name", "framedata1");
			map.put("id", id);
			decodingService.delete(map);
			result.put("success", true);
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
		}
		ResponseUtil.write(response, result);
		return null;
	}
	
	
	/**
	 * 导出Decoding
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/export")
	public String export(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		Workbook wb=new HSSFWorkbook();
		List<Decoding> decodingList = new ArrayList<Decoding>();
		String headers[]={"hdlc_id","触发时间","MSISDN","IMSI",
		"机车号","车次号","路局号","设备号 ","端口号",
		"时隙号","RBC名称","RBC号码","方向","CRC校验",	
		"NID_LRBG","公里标 ","速度","信令/C3数据类型","链路层 ",	
		"传输层","安全层","应用层"
		};
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		if(ids!=null&&!ids.equals("null")&&!ids.equals("")){
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("ids", idsList); 
			decodingList.clear();
			map.put("table_name", "framedata1");
			decodingList = decodingService.findByIds(map);
			
			try {
				ExcelUtil.fillExcelData_Decoding(decodingList, wb, headers);
				ResponseUtil.export(response, wb, "导出excel"+FormatDate.formatDate()+".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			decodingList.clear();
			map.put("table_name", "framedata1");
			decodingList = decodingService.find(map);
			try {
				ExcelUtil.fillExcelData_Decoding(decodingList, wb, headers);
				ResponseUtil.export(response, wb, "导出excel"+FormatDate.formatDate()+".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 用模板导出用户
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/exportByTemplate")
	public String exportByTemplate(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		List<Decoding> decodingList = new ArrayList<Decoding>();
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		if(ids!=null&&!ids.equals("null")&&!ids.equals("")){
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("ids", idsList); 
			decodingList.clear();
			map.put("table_name", "framedata1");
			decodingList = decodingService.findByIds(map);
			try {
				Workbook wb=ExcelUtil.fillExcelDataWithTemplate_Decoding(decodingList, "decodingExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel"+FormatDate.formatDate()+".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			decodingList.clear();
			map.put("table_name", "framedata1");
			decodingList = decodingService.find(map);
			try {
				Workbook wb=ExcelUtil.fillExcelDataWithTemplate_Decoding(decodingList, "decodingExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel"+FormatDate.formatDate()+".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}		
		}
		return null;
	}
	
	/**
	 * 用户上传
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/upload")
	public String upload(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JSONObject result=new JSONObject();
		Map<String,Object> map=new HashMap<String,Object>();
		 try{
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
       CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
       //检查form中是否有enctype="multipart/form-data"
       if(multipartResolver.isMultipart(request))
       {
           //将request变成多部分request
           MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
          //获取multiRequest 中所有的文件名
           Iterator iter=multiRequest.getFileNames();
           
          
           while(iter.hasNext())
           {
               //一次遍历所有文件
               MultipartFile file=multiRequest.getFile(iter.next().toString());
               if(file!=null)
               {
                   String path=PropertityUtil.UPLOAD_PATH+FormatDate.formatDate()+file.getOriginalFilename();
                   //上传
                   File newFile = new File(path);
                   file.transferTo(newFile);
                   //写数据进数据库
                   POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(newFile));
              		HSSFWorkbook wb=new HSSFWorkbook(fs);
              		HSSFSheet hssfSheet=wb.getSheetAt(0);  // 获取第一个Sheet页
              			if(hssfSheet!=null){
              				for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
              					HSSFRow hssfRow=hssfSheet.getRow(rowNum);
              					if(hssfRow==null){
              						continue;
              					}
              					Decoding decoding=new Decoding();
								decoding.setId(ExcelUtil.formatCell(hssfRow.getCell(0)));
								decoding.setHdlc_id(ExcelUtil.formatCell(hssfRow.getCell(1)));
								decoding.setStartTime(ExcelUtil.formatCell(hssfRow.getCell(2)));
								decoding.setMSISDN(ExcelUtil.formatCell(hssfRow.getCell(3)));
								decoding.setIMSI(ExcelUtil.formatCell(hssfRow.getCell(4)));
								decoding.setCTCS_ID(ExcelUtil.formatCell(hssfRow.getCell(5)));
								decoding.setTrainNumber(ExcelUtil.formatCell(hssfRow.getCell(6)));
								decoding.setVicroadNumber(ExcelUtil.formatCell(hssfRow.getCell(7)));
								decoding.setDeviceNumber(ExcelUtil.formatCell(hssfRow.getCell(8)));
								decoding.setPortNumber(ExcelUtil.formatCell(hssfRow.getCell(9)));
								decoding.setTimeSlot(ExcelUtil.formatCell(hssfRow.getCell(10)));
								decoding.setRBCName(ExcelUtil.formatCell(hssfRow.getCell(11)));
								decoding.setRBCNumber(ExcelUtil.formatCell(hssfRow.getCell(12)));
								decoding.setQ_DIR(ExcelUtil.formatCell(hssfRow.getCell(13)));
								decoding.setCRCTest(ExcelUtil.formatCell(hssfRow.getCell(14)));
								decoding.setNID_LRBG(ExcelUtil.formatCell(hssfRow.getCell(15)));
								decoding.setQ_MPOSITION(ExcelUtil.formatCell(hssfRow.getCell(16)));
								decoding.setSpeed(ExcelUtil.formatCell(hssfRow.getCell(17)));
								decoding.setSignalType(ExcelUtil.formatCell(hssfRow.getCell(18)));
								decoding.setLLayer(ExcelUtil.formatCell(hssfRow.getCell(19)));
								decoding.setTLayer(ExcelUtil.formatCell(hssfRow.getCell(20)));
								decoding.setSLayer(ExcelUtil.formatCell(hssfRow.getCell(21)));
								decoding.setALayer(ExcelUtil.formatCell(hssfRow.getCell(22)));
								decoding.setUUID(ExcelUtil.formatCell(hssfRow.getCell(23)));
								
								map.put("table_name","framedata1");
								map.put("id", decoding.getId());
								map.put("hdlc_id", decoding.getHdlc_id());
								map.put("TriggerTime", decoding.getStartTime());
								map.put("MSISDN", decoding.getMSISDN());
								map.put("IMSI", decoding.getIMSI());
								map.put("CTCS_ID", decoding.getCTCS_ID());
								map.put("TrainNumber", decoding.getTrainNumber());
								map.put("VicroadNumber", decoding.getVicroadNumber());
								map.put("DeviceNumber", decoding.getDeviceNumber());
								map.put("PortNumber", decoding.getPortNumber());
								map.put("TimeslotNumber", decoding.getTimeSlot());
								map.put("RBCName", decoding.getRBCName());
								map.put("RBCNumber", decoding.getRBCNumber());
								map.put("Q_DIR", decoding.getQ_DIR());
								map.put("CRCTest", decoding.getCRCTest());
								map.put("NID_LRBG", decoding.getNID_LRBG());
								map.put("Q_MPOSITION", decoding.getQ_MPOSITION());
								map.put("Speed", decoding.getSpeed());
								map.put("SignalType", decoding.getSignalType());
								map.put("LLayer", decoding.getLLayer());
								map.put("TLayer", decoding.getTLayer());
								map.put("SLayer", decoding.getSLayer());
								map.put("ALayer", decoding.getALayer());
								map.put("UUID", decoding.getUUID());
              					decodingService.add(map);
              				}
              			}
               }
           }
       }
       result.put("success", "true");
       } catch (Exception e) {
 			result.put("success", "false");
 			e.printStackTrace();
 		}
 		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 查找前置机列表
	 * @param 
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/decodingFrontProcessorIdComboList")
	public String decodingFrontProcessorIdComboList(HttpServletResponse response)throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject=new JSONObject();
		//System.out.println("开始找sitename" );
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		map.put("table_name","bs_info");
		List<String> FrontProcessorIds=decodingService.findFrontProcessorIds(map);
		for(int i=0;i<FrontProcessorIds.size();i++)
		{
			jsonObject.put("id", i);
			//String bs_name=alarmInfoService.get_bs_names();
			//System.out.println("FrontProcessorIds:" + FrontProcessorIds.get(i));
			jsonObject.put("name",FrontProcessorIds.get(i));
			jsonArray.add(jsonObject);
			
		}
		ResponseUtil.write(response, jsonArray);
		return null;
		/*JSONArray jsonArray=new JSONArray();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		map.put("table_name", PropertityUtil.DECODING_FRAMEDATA1_NAME);
		List<Decoding> decodingList = decodingService.findFrontProcessorIds(map);
		JSONArray rows=JSONArray.fromObject(decodingList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
		return null;*/
	}
	
	/**
	 * 查找IMSI列表
	 * @param 
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/decodingIMSIComboList")
	public String decodingIMSIComboList(HttpServletResponse response)throws Exception{
		JSONArray jsonArray=new JSONArray();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		map.put("table_name", PropertityUtil.DECODING_FRAMEDATA1_NAME);
		List<Decoding> decodingList = decodingService.findIMSIs(map);
		JSONArray rows=JSONArray.fromObject(decodingList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
		return null;
	}
	
	/**
	 * 查找MSISDN列表
	 * @param 
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/decodingMSISDNComboList")
	public String decodingMSISDNComboList(HttpServletResponse response)throws Exception{
		JSONArray jsonArray=new JSONArray();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		map.put("table_name", PropertityUtil.DECODING_FRAMEDATA1_NAME);
		List<Decoding> decodingList = decodingService.findMSISDNs(map);
		JSONArray rows=JSONArray.fromObject(decodingList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
		return null;
	}
	
	/**
	 * 查找CTCS_ID列表
	 * @param 
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/decodingCTCS_IDComboList")
	public String decodingCTCS_IDComboList(HttpServletResponse response)throws Exception{
		JSONArray jsonArray=new JSONArray();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("database_name", PropertityUtil.DECODING_DATABASE_NAME);
		map.put("table_name", PropertityUtil.DECODING_FRAMEDATA1_NAME);
		List<Decoding> decodingList = decodingService.findCTCS_IDs(map);
		JSONArray rows=JSONArray.fromObject(decodingList);
		jsonArray.addAll(rows);
		ResponseUtil.write(response, jsonArray);
		return null;
	}
}
